package com.vadmin.vadminjava.config;

import com.vadmin.vadminjava.common.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

/********************************************************************************
 *
 * 过滤器详细类
 *
 * ******************************************************************************/


public class MyFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		String requestUrl = ((HttpServletRequest) servletRequest).getRequestURI().toString();
		//System.out.println("自定义过滤器->doFilter,当前url:"+requestUrl);
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse resp = (HttpServletResponse) servletResponse;

		if( requestUrl.matches("/Admin(.*)") == true ){//如果是后台接口
			//System.out.println("是后台接口");

			//如果是登录接口，也放行
			if(requestUrl.matches("/AdminServlet/userLogin") == true){
				//System.out.println("但是是登录接口，放行");
				filterChain.doFilter(request, resp);
			}else{
				//System.out.println("是后台接口，进行token判断>>>>>>>>>>>>");
				if (JwtUtil.verify(((HttpServletRequest) request).getHeader("token")) != null) {
					//System.out.println("token验证通过！！！！！");
					filterChain.doFilter(request, resp);
				} else {
					System.out.println("token验证失几败.................");
					resp.setContentType("application/json;charset=utf-8");//这个也不行
					//resp.setStatus(406);//这个码可以自定义，和前端配合处理
					PrintWriter writer = resp.getWriter();
					writer.println("{\"resultFlag\":false,\"resultMsg\":\"token验证失败\"}");
					writer.close();
					//outPutOutputStream(resp);
				}
			}


		}else{//否则就放行
			//System.out.println("不是后台接口");
			filterChain.doFilter(request, resp);
		}


	}


	/**
	 *
	 * @方法名: outPutOutputStream
	 * @描述: 使用OutputStream输出流输出数据
	 * @param resp
	 * @throws IOException
	 * @创建人 zender
	 */
	private void outPutOutputStream(HttpServletResponse resp) throws IOException{
		String data = "{\"resultFlag\":false,\"resultMsg\":\"token验证失败\"}";
		//获取OutputStream输出流
		OutputStream outputStream = resp.getOutputStream();
		//将字符转换成字节数组，指定以UTF-8编码进行转换
		byte[] dataByteArr = data.getBytes("UTF-8");
		//使用OutputStream流向客户端输出字节数组
		outputStream.write(dataByteArr);
	}
	@Override
	public void destroy() {

	}



}